﻿//---------------------------------------------------------------------------------
// Copyright 2011 Microsoft Corporation
// Licensed under the Microsoft Public License (MS-PL) (the "License"); 
// You may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.opensource.org/licenses/ms-pl.html
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR 
// CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, 
// INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR 
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 
// MERCHANTABLITY OR NON-INFRINGEMENT. 
// See the Microsoft Public License (MS-PL) for the specific language governing 
// permissions and limitations under the License.
//---------------------------------------------------------------------------------
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using ControlTestApplications.WindowsPhoneApp.GatewayService;
using Microsoft.Phone.Controls;
using Microsoft.Telco.Controls.WindowsLive;
using Microsoft.Telco.Controls.WindowsPhone;

namespace ControlTestApplications.WindowsPhoneApp
{
    public partial class WPSamples : PhoneApplicationPage
    {

        private TimeSpan presenceRetrievalSpan = new TimeSpan(0, 0, 20);
        private System.Windows.Threading.DispatcherTimer updatePresenceTimer;
        GatewayServiceClient client;
        string errorMessage;
        
        public WPSamples()
        {
            InitializeComponent();
            updatePresenceTimer = new System.Windows.Threading.DispatcherTimer();
            updatePresenceTimer.Tick += new EventHandler(updatePresenceTimer_Tick);
            updatePresenceTimer.Interval = presenceRetrievalSpan;
            Loaded += (s, e) =>
            {
                GetContacts();
            };
        }


        void updatePresenceTimer_Tick(object sender, EventArgs e)
        {
            GetContacts();
        }


        void smsControl_SendSMSTriggerEvent(object sender, EventArgs e)
        {
            client = new GatewayServiceClient();
            ObservableCollection<string> coll = new ObservableCollection<string>();
            foreach (var item in smsControl.ToNumbers)
            {
                coll.Add(item);
            }

            switch (smsControl.Mode)
            {
                case SMSControlMode.SMS:
                    client.SendSMSCompleted += client_SendSMSCompleted;
                    client.SendSMSAsync(ServiceProperties.UserId, ServiceProperties.Origin, coll, smsControl.Message);
                    break;
                //case SMSControlMode.MMS:
                //    client.SendMMSCompleted += client_SendMMSCompleted;
                //    MMSDto dto = new MMSDto();
                //    dto.Subject = smsControl.Message;
                //    dto.Files = new ObservableCollection<MMSFileInfoDto>();
                //    foreach (var file in smsControl.Files)
                //    {
                //        dto.Files.Add(new MMSFileInfoDto { FileName = file.Name, Contents = GetBytesFromFile(file) });
                //    }
                //    client.SendMMSAsync(context, coll, dto);
                //    break;
                //default:
                //    break;
            }
        }

        void client_SendSMSCompleted(object sender, SendSMSCompletedEventArgs e)
        {
            if (!HasError(e))
            {
                client = new GatewayServiceClient();
                client.GetSMSStatusCompleted += client_GetSMSStatusCompleted;
                client.GetSMSStatusAsync(ServiceProperties.UserId, e.Result);
            }
            else
            {
                if (!string.IsNullOrEmpty(errorMessage))
                {
                    smsControl.UpdateStates(true, MessageState.SendingFailed, string.Format("Error: {0}", errorMessage));
                }
            }
        }

        void client_GetSMSStatusCompleted(object sender, GetSMSStatusCompletedEventArgs e)
        {
            if (!HasError(e))
            {
                var status = e.Result;
                smsControl.UpdateStates(true, MessageState.SentSuccessfully, string.Format("Status: {0}", status));
            }
            else
            {
                if (!string.IsNullOrEmpty(errorMessage))
                {
                    smsControl.UpdateStates(true, MessageState.SendingFailed, string.Format("Error: {0}", errorMessage));
                }
            }
        }

        private void GetContacts()
        {
            updatePresenceTimer.Stop();
            GatewayServiceClient client = new GatewayServiceClient();
            client.GetContactsCompleted += (s, e) =>
            {
                if (!HasError(e))
                {
                    //TODO: contactsControl.Contacts = TransformResult(e.Result);
                    updatePresenceTimer.Start();
                }
                else
                {
                    if (!(e.Error is FaultException<AuthenticationFault>))
                    {
                        MessageBox.Show("Error getting contacts: " + errorMessage);
                    }
                }

            };
            client.GetContactsAsync();
        }

        private ObservableCollection<WLCategoryContacts> TransformResult(ObservableCollection<LiveContact> coll)
        {
            var contacts = new ObservableCollection<WLCategoryContacts>();
            WLCategoryContacts category = new WLCategoryContacts();
            category.CategoryName = string.Empty;
            foreach (var item in coll)
            {
                category.CategoryContacts = new ObservableCollection<WLPresenceInfo>();
                category.CategoryContacts.Add(new WLPresenceInfo
                {
                    DisplayText = item.Name,
                    PresenceStatus = GetStatusFromPresenceStatus(item.PresenceStatus)
                });
                //TODO: presenceControl.UserNameOrEmail = item.Name;
                //TODO: presenceControl.UserStatus = GetStatusFromPresenceStatus(item.PresenceStatus);
                contacts.Add(category);
            }
            return contacts;
        }

        private Status GetStatusFromPresenceStatus(LivePresenceStatus cs)
        {
            Status status = Status.Unknown;
            switch (cs)
            {
                case LivePresenceStatus.Online:
                    status = Status.Available;
                    break;
                case LivePresenceStatus.Busy:
                    status = Status.Busy;
                    break;
                case LivePresenceStatus.Away:
                    status = Status.Away;
                    break;
                case LivePresenceStatus.Offline:
                    status = Status.Offline;
                    break;
                case LivePresenceStatus.Unknown:
                    status = Status.Unknown;
                    break;
            }
            return status;
        }

        private bool HasError(AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (e.Error is FaultException<AuthenticationFault>)
                {
                    //Authentication required
                    var fault = e.Error as FaultException<AuthenticationFault>;
                    ChildWindow authWin = new AuthPrompt(fault.Detail.ConsentUrl);
                    authWin.Closed += new EventHandler(authWin_Closed);
                    authWin.Show();
                    errorMessage = null;
                    return true;
                }
                else if (e.Error is FaultException<TelcoFault>)
                {
                    var fault = e.Error as FaultException<TelcoFault>;
                    errorMessage = fault.Detail.Message;
                }
                else
                {
                    errorMessage = e.Error.Message;
                }
                return true;
            }
            return false;
        }

        void authWin_Closed(object sender, EventArgs e)
        {
            // Need to add conditional
            GetContacts();
        }

        private void transcribeMediaControl_OnStartPlaying(object sender, EventArgs e)
        {
            GatewayServiceClient client = new GatewayServiceClient();
            client.ConvertTextToSpeechCompleted += new EventHandler<ConvertTextToSpeechCompletedEventArgs>(client_ConvertTextToSpeechCompleted);
            client.ConvertTextToSpeechAsync(transcribeMediaControl.Text);
        }
        
        void client_ConvertTextToSpeechCompleted(object sender, ConvertTextToSpeechCompletedEventArgs e)
        {
            if (!HasError(e))
            {
                transcribeMediaControl.InputAudioStream = new MemoryStream(e.Result.Content);
                transcribeMediaControl.Play();
            }
        }

        private void transcribeMediaControl_OnStopRecording(object sender, EventArgs e)
        {
            GatewayServiceClient client = new GatewayServiceClient();
            client.TranscribeVoiceCompleted += new EventHandler<TranscribeVoiceCompletedEventArgs>(client_TranscribeVoiceCompleted);
            Attachment attchment = new Attachment();
            attchment.Content = transcribeMediaControl.InputAudioStream.ToArray();
            client.TranscribeVoiceAsync(attchment);
        }

        void client_TranscribeVoiceCompleted(object sender, TranscribeVoiceCompletedEventArgs e)
        {
            if (!HasError(e))
            {
                transcribeMediaControl.Text = e.Result;
            }
        }

        private void transcribeMediaControl_Loaded(object sender, RoutedEventArgs e)
        {
            transcribeMediaControl.Text = "Here is the sample text to test for the transcribe media control.";
        }
    }
}